'use strict';

const Service = require('egg').Service;

class ReadyService extends Service {
  async found(arg) {
    const { app, ctx } = this;
    const socket = arg.id;
    const player = arg.userName;
    const active = player;
    const room = await app.mysql.get('room', { roomnum: arg.roomNum });
    if (!room) { // 如果数据库房间不存在则创建
      await app.mysql.insert('room', { roomnum: arg.roomNum, player, active, peoplenum: 1, householder: arg.userName, socket, prepare: 1, dealer: 0, at: 0 });
    } else {
      room.socket = room.socket + '|' + socket;
      room.player = room.player + '|' + player;
      room.active = room.player;
      room.peoplenum += 1;
      await app.mysql.update('room', room);
    }
    const outroom = await app.mysql.get('room', { roomnum: arg.roomNum });
    ctx.socket.join(arg.roomNum);
    ctx.socket.in(arg.roomNum).emit('sys', { msg: arg.userName + '加入了房间', outroom });// 发送系统消息
    outroom ? outroom.code = 200 : outroom.code = 404;
    return outroom;
  }

  async leave(arg) { // 玩家离开房间
    const { app, ctx } = this;
    const outroom = await app.mysql.get('room', { roomnum: arg.roomNum });
    const playerArr = outroom.player.split('|');
    const socketArr = outroom.socket.split('|');
    playerArr.forEach((e, i) => {
      if (e === arg.userName) {
        playerArr.splice(i, 1);
      }
    });
    socketArr.forEach((e, i) => {
      if (e === arg.id) {
        socketArr.splice(i, 1);
      }
    });
    outroom.player = playerArr.toString();
    outroom.active = outroom.player;
    outroom.socket = socketArr.toString();
    outroom.peoplenum = playerArr.length;
    await app.mysql.update('room', outroom);
    ctx.socket.leave(arg.roomNum);
    ctx.socket.in(arg.roomNum).emit('sys', { msg: arg.userName + '离开了房间', outroom });
  }
}

module.exports = ReadyService;
